package com.javaex.book.utils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 根据返回值类型对参数进行类型转换
 *
 * @author 黄星琦
 * @Date 2022年2月14日
 */
public class TypeConvertUtils {

	private static final Logger logger = LoggerFactory.getLogger(TypeConvertUtils.class);
	private static final Map<Class<?>, Function<String, Object>> map = new HashMap<Class<?>, Function<String, Object>>();
	
	static {
		map.put(String.class, value -> value);
		map.put(int.class, value -> {
			try {
				return Integer.parseInt(value);
			} catch (Exception e) {
				return 0;
			}
		});
		map.put(Integer.class, value -> {
			try {
				return Integer.parseInt(value);
			} catch (Exception e) {
				return 0;
			}
		});
		map.put(BigDecimal.class, value -> {
			try {
				return new BigDecimal(value);
			} catch (NumberFormatException e) {
				return new BigDecimal(0);
			}
		});
		map.put(boolean.class, value -> Boolean.valueOf(value));
		map.put(Boolean.class, value -> Boolean.valueOf(value));
		logger.info("TypeConvertUtils.map 初始化完毕");
		logger.debug("TypeConvertUtils.map 初始化完毕", LoggerUtils.mapToString(map));
	}
	
	/**
	 * 值value类型转换
	 * @param type 目标类型
	 * @param value 值
	 * @return 转换类型后的值
	 */
	public static Object typeConvert(Class<?> type, String value) {
		Function<String, Object> function = map.get(type);
		if (function == null) {
			return null;
		}
		return function.apply(value);
	}
}
